import csv
import numpy as np
import pandas as pd
from pandas.plotting import parallel_coordinates
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import collections
from matplotlib.colors import ListedColormap
# from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA


# def errCounter(res,standard):
# 	errRate=0
# 	for i in range(res.shape[0]):
# 	if res[i]!=standard[i]:
# 		errRate+=1

# 	return errRate/res.shape[0]


def simplePCA(raw,dimen=1):
	pca=PCA(n_components=dimen,copy=True)
	newData=pca.fit_transform(raw)
	return newData




def file2fullMatrix(filename):            #取出全部的特征
	with open(filename) as csvfile:
		spamReader=csv.reader(csvfile)
		listReader=np.array(list((spamReader)))[:,1:]
	

		height=len(listReader)
		width=len(listReader[1])

		# print(height)
		# print(width)


		feature=np.zeros((height-2,width-1))
		target=[]
		feature_name=listReader[1,:]
		for i in range(2,height):
			feature[i-2,]=listReader[i][:width-1]
			target.append(listReader[i][width-1])

		
		return feature,np.array(target),feature_name


def file2xMatrix(filename,num=2):        #只取前n个特征,用来简单地测试
	with open(filename) as csvfile:
		spamReader=csv.reader(csvfile)
		listReader=np.array(list((spamReader)))[:,1:]
	

		height=len(listReader)
		width=len(listReader[1])

		# print(height)
		# print(width)a


		feature=np.zeros((height-2,num))
		target=listReader[:,-1]
		feature_name=[listReader[1][i] for i in range(0,num)]
		
		for i in range(num):
			feature[:,i]=listReader[2:,i]
			# target.append(listReader[i][width-1])

		
		return feature,target,feature_name



def autoNorm(dataSet):       #规格化数据
	minVals=dataSet.min(0)
	maxVals=dataSet.max(0)

	ranges=maxVals-minVals


	normDataSet=(dataSet-minVals)/ranges

	return normDataSet



def colorGen(numb):	  #把数字变成对应的颜色
	if numb=='0':
		return 'b'

	if numb=='1':
		return 'orange'



def showTwoDimen(filename,m,n):   #对某两个维度画图
	mat,tag,feature_name=file2fullMatrix(filename)
	width=mat.shape[1]
	if m>=width:
		print("the first number should be less than %d" %width)
		return

	if n>=width:
		print("the second number should be less than %d" %width)
		return



	color=[colorGen(i) for i in tag]


	dimen1=mat[:,m]
	min_x=np.min(dimen1,axis=0)
	max_x=np.max(dimen1,axis=0)


	dimen2=mat[:,n]
	min_y=np.min(dimen2,axis=0)
	max_y=np.max(dimen2,axis=0)	


	fig1=plt.figure(1)
	ax1=plt.subplot(1,1,1)
	ax1.set_xlim(min_x,max_x)
	ax1.set_ylim(min_y,max_y)


	ax1.scatter(dimen1,dimen2,color=color,alpha=0.4)

	line1=mlines.Line2D([],[],color="b",marker='o',linestyle='',label='healthy')
	line2=mlines.Line2D([],[],color='orange',marker='o',linestyle='',label='unhealthy')

	plt.legend(handles=[line1,line2])

	plt.show()



def showAllDimen(filename):                          #多维画图
	mat,tag,feature_name=file2fullMatrix(filename)
	mat=autoNorm(mat)
	# print(feature_name)
	data_dict=dict()
	


	column=0
	columnLimit=10   #有几个纵轴
	man=200          #有几个人

	for name in feature_name:
		data_dict[name]=mat[:man, column]
		column+=1
		if column==columnLimit:
			break

	data_dict["tags"]=tag[:man]
	

	pd_data=pd.DataFrame(data_dict)
	fig1=plt.figure(1)
	parallel_coordinates(pd_data,"tags",color=('#87CEFA','#FFA07A'))

	plt.show()







if __name__=='__main__':
	filename="pd_speech_features.csv"
	a,b,c=file2xMatrix(filename)
	# showAllDimen(filename)

